//
//  HMUserAccountViewModel.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/2.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class HMUserAccountViewModel: NSObject {
    // 当前 viewModel 对应的模型
    var account :HMUserAccount?
    var accessToken : String?{
        return account?.access_token
    }
    
    static let sharedModel:HMUserAccountViewModel =
    HMUserAccountViewModel()
    
    /// 当前用户是否登录
    var userLogon : Bool{
        if account?.access_token != nil && isExpires == false {
            return true
        }
        return false
    }
    
    /// 代表当前帐户是否过期
    var isExpires : Bool {
        if let expiresDate = account?.expiresDate {
            if expiresDate.compare(Date()) == .orderedDescending {
                return false
            }
        }
        return true
    }
    
    override init() {
        super.init()
        // 如果用户在第一次进入软件登录了之后，保存了用户信息
        // 那么在第二次进入软件就不用去登录了，直接从沙盒中将用户的信息保存到内存中
        account = self.loadUserAccout()
    }
    
    
    // MARK: - 私有方法
    func loadAccessToken(code:String,completion:@escaping (Bool)->())  {
        // 请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求的参数
        let params = [
            "client_id": WB_APPKEY,
            "client_secret": WB_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URI
        ];
        // 使用afn发起请求
        HMNetworkTools.sharedTools.request(method: .Post, urlString: urlString, parameters: params) { (response, error) in
            if response == nil || error != nil {
                print("请求错误\(error)")
                return
            }
            // 进行字典转模型
            let acount = HMUserAccount(dict: response!as![String:Any])
            
            
            // 代码走到这一步，就代表accessToken获取完成
            self.loadUserInfo(account: acount,completion:completion)
            
        }
        
    }
    
    //MARK:-获取用户的个人信息
    private func loadUserInfo(account:HMUserAccount,completion:@escaping (Bool)->())  {
        // 定义请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 定义请求参数
        let params = ["access_token":(account.access_token  ?? ""),"uid":(account.uid ?? "")]
        // 发起请求
        HMNetworkTools.sharedTools.request(method: .Get, urlString: urlString, parameters: params) { (response, error) in
            if response == nil || error != nil {
                print("请求错误\(error)")
                return
            }
            // 接下来要做的事情就是将头像与昵称保存起来
            let dict = response! as! [String:Any]
            account.name = dict["name"] as? String
            account.profile_image_url = dict["profile_image_url"] as? String
            
            //进行归档保存
            self.saveAccount(account: account)
            self.account = account
            completion(true)
        }
    }
    //MARK: - 保存用户的信息
    private func saveAccount(account:HMUserAccount){
        
        
        //1. 获取到文件路径
        let  file = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        print(file)
        // 2. 归档
        NSKeyedArchiver.archiveRootObject(account, toFile: file)
    }
    
     //MARK: -加载用户信息的方法
    private func loadUserAccout()->HMUserAccount?{
        let  file = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        print(file)
        return NSKeyedUnarchiver.unarchiveObject(withFile: file) as? HMUserAccount

    }

}
